<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;
use think\Session;

// 应用公共文件
//封装密码的加密文件
if (!function_exists('encrypt_password')) {
    //定义密码的加密函数
    function encrypt_password($password, $salt = '')
    {
        if (!$salt) {
            $salt = mt_rand(10000, 99999);
        }
        $password = md5(md5($password) . $salt);
        return array('salt' => $salt, 'password' => $password);
    }
}
// 生成随机字符串
if (!function_exists('generatePassword')) {
    function generatePassword($length = 6)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $password = "";
        for ($i = 0; $i < $length; $i++) {
            $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $password;
    }
}
//获取用户的ip
if (!function_exists('getIp')) {
    function getIP()
    {
        static $ip = NULL;
        if ($ip !== NULL) return $ip;

        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else if (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        //IP地址合法验证
        $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
        return $ip;
    }
}
//删除文件夹及其下面的所有文件
if (!function_exists('delFile')) {
    function delFile($dir)
    {
        $dh = opendir($dir);//打开文件夹
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (is_dir($fullpath)) {
                    delFile($fullpath);
                } elseif (is_file($fullpath) && isset($fullpath)) {
                    unlink($fullpath);
                }
            }
        }
        closedir($dh);
        rmdir($dir);
    }
}
//匹配用户名
if (!function_exists('pregUser')) {
    //匹配用户名
    function pregUser($text, $min = 1, $max = 8)
    {
        $rule = '/^[a-zA-Z\x{4e00}-\x{9fa5}0-9_]{' . $min . ',' . $max . '}$/u';
        preg_match($rule, $text, $result);
        return $result;
    }
}
//匹配手机号码
if (!function_exists('pregPN')) {
    function pregPN($text)
    {
        $rule = "/^1\d{10}$/";
        preg_match($rule, $text, $result);
        return $result;
    }
}
//匹配邮箱
if (!function_exists('pregMAIL')) {
    function pregMAIL($text)
    {
        $rule = "/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/";
        preg_match($rule, $text, $result);
        return $result;
    }
}
//匹配身份证
if (!function_exists('precard')) {
    function precard($card)
    {
        $rule = "/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/";
        preg_match($rule, $card, $result);
        return $result;
    }
}
//验证密码
if (!function_exists('pregPW')) {
    function pregPW($text, $min = 6, $max = 32)
    {
        $rule = '/^[a-zA-Z0-9_]{' . $min . ',' . $max . '}$/';
        preg_match($rule, $text, $result);
        return $result;
    }
}
//封装一个无限极分类
if (!function_exists('getTree')) {
    //递归方法实现无限极分类
    function getTree($list, $pid = 0, $level = 0, $pidre = null)
    {
        static $tree = array();
        foreach ($list as $row) {
            if (!$pidre) {
                if ($row['pid'] == $pid) {
                    $row['level'] = $level;
                    $tree[] = $row;
                    getTree($list, $row['id'], $level + 1, $pidre);
                }
            } else {
                if ($row[$pidre] == $pid) {
                    $row['level'] = $level;
                    $tree[] = $row;
                    getTree($list, $row['id'], $level + 1, $pidre);
                }
            }
        }
        return $tree;
    }
}

if (!function_exists('getTrees')) {
    //递归方法实现无限极分类
    function getTrees($list, $pid = 0, $level = 0)
    {
        static $tree = array();
        foreach ($list as $row) {
            if ($row['pid'] == $pid) {
                $row['level'] = $level;
                $tree[] = $row;
                getTrees($list, $row['account_id'], $level + 1);
            }
        }
        return $tree;
    }
}


// 无限分类，查找子级
if (!function_exists('getTreeData')) {
    function getTreeData($table, $field, $where = '1=1', $pid = 0, $data = array())
    {
        $_data = Db::name($table)
            ->field($field)
            ->where($where)
            ->where('pid', $pid)
            ->order('drank asc')
            // ->fetchSql()
            ->select();
        // var_dump($data);die;
        if (!empty($_data)) {
            foreach ($_data as $k => $v) {
                $data[$k] = $_data[$k];
                $res = getTreeData($table, $field, $where, $v['id']);
                if (!empty($res)) {
                    $data[$k]['child'] = $res;
                }
                // var_dump($data);die;
            }
            return $data;
        } else {
            return $data;
        }
    }
}


// 无限分类，多表联查
if (!function_exists('getTreeDatas')) {
    function getTreeDatas($table, $join, $field, $where = '1=1', $pid = 0, $data = array())
    {
        $_data = Db::name($table)
            ->alias('zu')
            ->join($join)
            ->field($field)
            ->where($where)
            ->where('zu.pid', $pid)
            ->order('zu.drank asc')
            ->select();
        if (!empty($_data)) {
            foreach ($_data as $k => $v) {
                $data[$k] = $_data[$k];
                $res = getTreeDatas($table, $join, $field, $where, $v['id']);
                if (!empty($res)) {
                    $data[$k]['child'] = $res;
                }
            }
            return $data;
        } else {
            return $data;
        }
    }
}


//无限极分类
if (!function_exists('getFrames')) {
    function getFrames($department = 'department', $lang = null, $country_id = 0)
    {
        //获取当前用户的信息
        $admin = session('admin');
        switch ($department) {
            case 'department':
                $fid = $admin['department_id'];//部门id
                break;
            case 'position':
                $fid = $admin['position_id'];//职位id
                break;
            default:
                $fid = $admin['department_id'];//传过来的id
                break;
        }
        if ($admin['position_id'] != 1) {
            //不是管理员
            $rs = getInfiniteSort($department, $lang, $country_id, $fid);
            //将自己本身的数据追加进去
            $info = getinfo($fid, $department);
            if ($lang) {
                //有语言获取一个
                $deposwhere['mkey'] = $info['mkey'];
                $info['langname'] = getlangname('multi_lang', $deposwhere, $lang);
            } else {
                //没有语言获取多个
                $langname = Db::name('multi_lang')->field('lang,content')->where('mkey', $info['mkey'])->select();
                foreach ($langname as $langnamekey => $langnameval) {
                    $info[$langnameval['lang'] . 'name'] = $langnameval['content'];
                }
            }
            $info['level'] = 1;
            $rs[count($rs) + 1] = $info;
            foreach ($rs as $rskey => $rsval) {
                $rs[$rskey]['level'] = $rsval['level'] + 1;
            }
        } else {
            $rs = getInfiniteSort($department, $lang, $country_id, 0);
        }
        if (!empty($rs)) sort($rs);
        return $rs;
    }
}
//获取无限分类
if (!function_exists('getInfiniteSort')) {
    function getInfiniteSort($db_name, $lang, $country_id, $uid = 0, $i = 0)
    {
        $whereor = array();
        $i++;
        //获取这个部门下的子部门
        $where['pid'] = $uid;
        $where['country_id'] = ['in', $country_id];
        $rs = Db::name($db_name)->where($where)->select();//获取数据
        if ($lang) {
            //含有语言获取一个
            foreach ($rs as $rskey => $rsval) {
                $rs[$rskey]['langname'] = Db::name('multi_lang')->where(['mkey' => $rsval['mkey'], 'lang' => $lang])->value('content');
            }
        } else {
            //没有获取多个
            foreach ($rs as $rskey => $rsval) {
                $langname = Db::name('multi_lang')->field('lang,content')->where('mkey', $rsval['mkey'])->select();
                foreach ($langname as $langnamekey => $langnameval) {
                    $rs[$rskey][$langnameval['lang'] . 'name'] = $langnameval['content'];
                }
            }
        }
        $return = array();
        foreach ($rs as $value) {
            $value['level'] = $i;
            $return[] = $value;
            foreach (getInfiniteSort($db_name, $lang, $country_id, $value['id'], $i) as $value_2) {
                $return[] = $value_2;
            }
        }
        return $return;
    }
}

// 无限分类子级
if (!function_exists('getTreeChild')) {
    function getTreeChild($isChild = true, $table, $where = '1=1', $lang = null, $pid = 0, $data = array())
    {
        $_data = Db::name($table)
            ->where($where)
            ->where('pid', $pid)
            // ->order('drank asc')
            ->select();
        if ($lang) {
            //获取一种
            foreach ($_data as $_datakey => $_dataval) {
                $_data[$_datakey]['langname'] = Db::name('multi_lang')->where(['mkey' => $_dataval['mkey'], 'lang' => $lang])->value('content');
            }
        } else {
            //获取多种
            foreach ($_data as $_datakey => $_dataval) {
                $langname = Db::name('multi_lang')->field('lang,content')->where('mkey', $_dataval['mkey'])->select();
                foreach ($langname as $langnamekey => $langnameval) {
                    $_data[$_datakey][$langnameval['lang'] . 'name'] = $langnameval['content'];
                }
            }
        }
        if (!empty($_data)) {
            foreach ($_data as $k => $v) {
                $data[] = $_data[$k];
                $res = getTreeChild($isChild, $table, $where, $lang, $v['id']);
                if (!empty($res)) {
                    if ($isChild) {
                        $data[$k]['child'] = $res;
                    } else {
                        foreach ($res as $key => $value) {
                            array_push($data, $value);
                        }
                    }
                }
            }
            return $data;
        } else {
            return $data;
        }
    }
}

if (!function_exists('removeBlank')) {
    function removeBlank($str)
    {
        $qian = array(" ", "　", "", "\t", "\n", "\r");
        $hou = array("", "", "", "", "");
        return str_replace($qian, $hou, $str);
    }
}

/*
导出
$title 文件名
$head 表头
$data 数据
$separate 是否分割
$iconSize 图片大小
$fontSize 字体大小
*/
function export($title, $head, $data, $separate, $fontSize, $iconSize)
{
    $onea = $oneb = $onec = '';
    require('./PhpExcel/PHPExcel/IOFactory.php');
    $obj_php_excel = new \PHPExcel(); //创建一个实例
    $obj_php_excel->setActiveSheetIndex(0);//把新创建的sheet设定为当前活动sheet
    $objsheet = $obj_php_excel->getActiveSheet();//获取当前的活动的sheet的对象
    $objsheet->getHeaderFooter()->setOddHeader( '&L&G&C&HPlease treat thisdocument as confidential!');
//    $objsheet->getHeaderFooter()->setOddFooter( '&L&B' .$objsheet->getProperties()->getTitle(). '&RPage &P of&N' );
    //第一行
    $objsheet->getDefaultStyle()->getFont()->setName('微软雅黑')->setSize($fontSize);//设置默认字体的大小
    $objsheet->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//设置垂直居中
    $objsheet->getStyle('A1:K1')->getFont()->getColor()->setRGB('999999');
    //设置页眉
    $one = "EXBOM货运清单 货柜：" . $data['huodata']['code'] . "\r\n装柜时间：" . $data['huodata']['arrival_day'];
    $objsheet->getStyle('A1:' . 'I1')->getAlignment()->setWrapText(true);//设置列自动换行
    $objsheet->getRowDimension(1)->setRowHeight(60);//设置页眉高度
    $objsheet->getStyle('A1:K1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('ffffff');//填充颜色
    $objsheet->setCellValue('A1', $one);
    $objsheet->mergeCells('A1:' . 'I1');//合并左侧的单元格;
    $objsheet->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//靠左对齐
    //设置打印时间
    $two = '打印时间:' . getTimeDate(null);
    $objsheet->setCellValue('J1', $two);
    $objsheet->mergeCells('J1:' . 'K1');//合并右侧的单元格;
    $objsheet->getStyle('J1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); //靠右对齐
    $objsheet->getStyle('J1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_BOTTOM);//设置靠下
    //第二行
    foreach ($head as $key => $value) {
        $line = 2;
        $index = PHPExcel_Cell::stringFromColumnIndex($key);
        $station = $index . $line;
        // 垂直居中
        $objsheet->getStyle($station)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        // 标题居左
        $objsheet->getStyle($station)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        // 设置背景颜色
        $objsheet->getStyle($station)->getFill()
            ->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()->setRGB('6690a0');//填充颜色
        $objsheet->getRowDimension($line)->setRowHeight(30);//设置标题高度
        // 设置字体颜色
        $objsheet->getStyle($station)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
        // 设置内容
        $objsheet->setCellValue($station, $value);
    }
    //对数据的渲染
    $j = 3;
    $summ3=$sumqty=$sumkgs=0;
    if ($separate == 1) {
        //只有产品
        foreach ($data['prodata'] as $datakeys => $datavals) {
            foreach ($head as $keys => $values) {
                $indexs = PHPExcel_Cell::stringFromColumnIndex($keys);//对应坐标
                $width = getwidth($indexs, $data['prodata'][0]);//对应宽度
                $objsheet->getColumnDimension($indexs)->setWidth($width);//对应的单元格宽度
                if ($indexs == 'A' || $indexs == 'B' || $indexs == 'C') {
                    $objsheet->getStyle($indexs.$j)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//靠左
                } else {
                    $objsheet->getStyle($indexs.$j)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);//靠右
                }
                //各行换色
                if (is_int($j / 2)) {
                    //偶数
                    $objsheet->getStyle($indexs.$j)->getFill()
                        ->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)
                        ->getStartColor()->setRGB('f2f6f7');//填充颜色
                } else {
                    //奇数
                    $objsheet->getStyle($indexs.$j)->getFill()
                        ->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)
                        ->getStartColor()->setRGB('e2e8e9');//填充颜色
                }
            }
            //file_put_contents("test.txt", "传入数据 = " . json_encode($datakeys) . "\r\n", FILE_APPEND);
            if ($datavals['brand_name']) {
                $onea = $datavals['brand_name'] . '/ ';
            }
            if ($datavals['model']) {
                $oneb = $datavals['model'];
            }
            if ($datavals['pro_name']) {
                $onec = $datavals['pro_name'];
            }
            $c = '产品 / ' . $onea . '型号:' . $oneb . "\r\n" . $onec;
            $objsheet->getStyle('C' . $j)->getAlignment()->setWrapText(true);//设置换行
            //将数据插入表格
            $objDrawing = new \PHPExcel_Worksheet_Drawing();//获得一个图片的操作的对象
            //对图片的插入
            $objDrawing->setPath(ltrim($datavals['img_url'], '/'));//图片存放的路径
            $objDrawing->setCoordinates('B' . $j);//设置图片左上角的坐标
            $objDrawing->setWidth($iconSize['width']);//设置图片的宽度
            $objDrawing->setHeight($iconSize['height']);//设置图片的宽度
            $objsheet->getRowDimension($j)->setRowHeight($iconSize['height']);//设置单元格高度
            $objDrawing->setOffsetX(15);
            $objDrawing->setOffsetY(10);
            $objDrawing->setWorksheet($objsheet);//将图片插入到sheet中
            $objsheet->setCellValue('A' . $j, $datavals['prochar_id'])->setCellValue('C' . $j, $c)->setCellValue('D' . $j, $datavals['qty'])->setCellValue('E' . $j, $datavals['ctn_qty'])->setCellValue('F' . $j, $datavals['ctn_size'])->setCellValue('G' . $j, $datavals['ctn_kgs'])->setCellValue('H' . $j, $datavals['ctn_m3'])->setCellValue('I' . $j, $datavals['qty_sum'])->setCellValue('J' . $j, $datavals['m3_sum'])->setCellValue('K' . $j, $datavals['ksg_sum']);
            $summ3+=$datavals['m3_sum'];
            $sumqty+=$datavals['qty'];
            $sumkgs+=$datavals['ksg_sum'];
            $j++;
        }
    } else {
        //以合同进行分割
        foreach ($data['prodata'] as $datakey => $dataval) {
            $objsheet->getStyle('A' . $j)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//左右靠左
            $dataone = '合同号：' . numzero($dataval['po_id']) . ' / ' . $dataval['company_name'] . ' / 交货时间:' . $dataval['delivery_day'];
            $objsheet->setCellValue('A' . $j, $dataone);
            $objsheet->mergeCells('A' . $j . ":" . 'K' . $j);//合并单元格
            $objsheet->getStyle('A' . $j . ":" . 'K' . $j)->getFill()
                ->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)
                ->getStartColor()->setRGB('b0e0f0');//填充颜色

            //对每一个数据进行填充
            $j = $j + 1;
            foreach ($dataval['pro'] as $datavalkey => $datavalval) {
                foreach ($head as $keyss => $valuess) {
                    $indexsss = PHPExcel_Cell::stringFromColumnIndex($keyss);//对应坐标
                    $width = getwidth($indexsss, $dataval['pro'][0]);//对应宽度
                    $objsheet->getColumnDimension($indexsss)->setWidth($width);//对应的单元格宽度
                    if ($indexsss == 'A' || $indexsss == 'B' || $indexsss == 'C') {
                        $objsheet->getStyle($indexsss.$j)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);//靠左
                    } else {
                        $objsheet->getStyle($indexsss.$j)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);//靠右
                    }
                }
                $objDrawing = new \PHPExcel_Worksheet_Drawing();//获得一个图片的操作的对象
                //对图片的插入
                $objDrawing->setPath(ltrim($datavalval['img_url'], '/'));
                $objDrawing->setCoordinates('B' . $j);//设置图片左上角的坐标
                $objDrawing->setWidth($iconSize['width']);//设置图片的宽度
                $objDrawing->setHeight($iconSize['height']);//设置图片的宽度
                $objsheet->getRowDimension($j)->setRowHeight($iconSize['height']);//设置单元格高度
                //设置偏移量
                $objDrawing->setOffsetX(15);
                $objDrawing->setOffsetY(10);
                $objDrawing->setWorksheet($objsheet);//将图片插入到sheet中
                if ($datavalval['brand_name']) {
                    $onea = $datavalval['brand_name'] . '/ ';
                }
                if ($datavalval['model']) {
                    $oneb = $datavalval['model'];
                }
                if ($datavalval['pro_name']) {
                    $onec = $datavalval['pro_name'];
                }
                $c = '产品 / ' . $onea . '型号:' . $oneb . "\r\n" . $onec;
                $objsheet->getStyle('C' . $j)->getAlignment()->setWrapText(true);//设置换行
                $objsheet->setCellValue('A' . $j, $datavalval['prochar_id'])->setCellValue('C' . $j, $c)->setCellValue('D' . $j, $datavalval['qty'])->setCellValue('E' . $j, $datavalval['ctn_qty'])->setCellValue('F' . $j, $datavalval['ctn_size'])->setCellValue('G' . $j, $datavalval['ctn_kgs'])->setCellValue('H' . $j, $datavalval['ctn_m3'])->setCellValue('I' . $j, $datavalval['qty_sum'])->setCellValue('J' . $j, $datavalval['m3_sum'])->setCellValue('K' . $j, $datavalval['ksg_sum']);
                $summ3+=$datavalval['m3_sum'];
                $sumqty+=$datavalval['qty'];
                $sumkgs+=$datavalval['ksg_sum'];
                $j++;
            }
        }
    }
    //设置合计（箱数、体积、重量）
    $str='合计箱数: '.$sumqty.'CTN， 合计体积：'.$summ3.'CBM, 合计重量: '.$sumkgs.'KGS';
    $start='A'.$j;
    $end='K'.$j;
    $objsheet->mergeCells("$start:" ."$end");//合并右侧的单元格;
    $objsheet->getStyle("$start:" ."$end")->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('6690a0');//填充颜色
    $objsheet->getStyle($start)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); //靠右对齐
    $objsheet->setCellValue($start, $str);
    //设置宽度
    $objWriter = \PHPExcel_IOFactory::createWriter($obj_php_excel, 'Excel5');//生成excel文件
    $objsheet->setTitle($title);
    brower_export('Excel5', $title);//输出到浏览器
    $objWriter->save("php://output");//输出到浏览器的代码
}

//使用内容设置对应的宽度
function getwidth($index, $datavals)
{
    switch ($index) {
        case 'A':
            $width = (strlen($datavals['prochar_id']) * 2);
            break;
        case 'B':
            $width = 8;
            break;
        case 'C':
            $width = 35;
            break;
        case 'D':
            $width = (strlen($datavals['qty']) * 4);
            break;
        case 'E':
            $width = (strlen($datavals['ctn_qty']) * 4);
            break;
        case 'F':
            $width = (strlen($datavals['ctn_size']) * 2);
            break;
        case 'G':
            $width = 12;
            break;
        case 'H':
            $width = (strlen($datavals['ctn_m3']) * 4);
            break;
        case 'I':
            $width = (strlen($datavals['qty_sum']) * 4);
            break;
        case 'J':
            $width = 15;
            break;
        case 'K':
            $width = 15;
            break;
        default:
            $width = 55;
            break;
    }
    return $width;
}


function brower_export($type, $filename)
{
    if ($type == 'Excel5') {
        header('Content-Type: application/vnd.ms-excel');//告诉浏览器输出excel03文件
    } else {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出excel07文件
    }
    header('Content-Disposition:attachment;filename="' . $filename . '.xls"');//告诉浏览器的输出文件的名称
    header('Cache-Control: max-age=0');//禁止浏览器缓存

}

//php打印pdf
function pdfphp()
{
    require('./tcpdf/tcpdf.php');
    //实例化
    $content = '我是一个pdf';  //你要生成的PDF内容
    $pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
    // 设置文档的属性信息
    $pdf->SetCreator('Lane');//文档创建者名称
    $pdf->SetAuthor('Lane');//设置作者
    $pdf->SetTitle('PHP生成PDF');//设置文档标题
    $pdf->SetSubject('PHP动态生成PDF文件');
    $pdf->SetKeywords('PHP PDF TCPDF');//文档关键词)

    //设置页眉信息 参数分别是LOGO地址，LOGO宽度，页眉标题，页眉的说明文字，文本的rgb颜色(黑色)页眉下划线的颜色（黑色）
    $pdf->SetHeaderData('/static/Admin/img/login_bg_1920x1080.jpg', 30, 'PHP生成PDF', 'PHP如何生成PDF文件', array(0, 0, 0), array(0, 0, 0));
    //设置页脚信息
    $pdf->setFooterData(array(0, 0, 0), array(0, 0, 0));
    // 分别是设置页眉的字体 font-family，font-style，font-size
    $pdf->setHeaderFont(Array('stsongstdlight', '', '12'));

    // 页脚文本颜色和下划线的颜色
    $pdf->setFooterFont(Array('helvetica', '', '8'));
    //    如果不希望使用页眉页脚，可以使用setPrintHeader和setPrintFooter方法关闭页眉页脚，只要传递参数false即可。

    //设置默认等宽字体
    $pdf->SetDefaultMonospacedFont('courier');
    //正文间距
    $pdf->SetMargins(15, 27, 15);
    //页眉的间距
    $pdf->SetHeaderMargin(5);
    //页脚的间距
    $pdf->SetFooterMargin(10);

    //设置分页 是否开启分页 ，页面距底部的距离
    $pdf->SetAutoPageBreak(TRUE, 15);
    //新添分页
    $pdf->AddPage();
    //设置图片比例
    $pdf->setImageScale(1.25);

    //设置字体 - 正文标题的哦。B是加粗，15是大小 stsongstdlight 可以防止中文乱码
    $pdf->SetFont('stsongstdlight', 'B', 15);
    //有12 个参数 $h表示行高，$txt表示要打印的内容
    $pdf->Write(20, 'PHP生成动态pdf', '', 0, 'C', true, 0, false, false, 0);

    //如果html中含有css的话 使用writeHTML方法 该方法有6个参数，但必填的只有一个就是需要打印的内容，其他的参数可以是默认值

    //设置字体 - 正文内容的哦。B是加粗，15是大小
    $pdf->SetFont('stsongstdlight', '', 10);

    //L是左对齐，R是右对齐，C是居中对齐。
    $pdf->Write(0, $content, '', 0, 'L', true, 0, false, false, 0);

    //输出PDF。第二个参数默认是I，是浏览器预览。D是下载
    $pdf->Output('PHP_TO_PDF.pdf', 'D');
}

//实现用户的操作记录的操作
if (!function_exists('setRecord')) {
    function setRecord($action, $text, $model = null)
    {
        $data['uid'] = session('userid');
        if ($action == 4 || $action == 5) {
            if (strpos($text, '-') != false) { //添加登录失败记录
                $textArr = explode('-', $text);
                $umap['dadmin'] = $textArr[1];
                //根据用户名查找ID
                $uInfo = Db::name('admin')->where($umap)->find();
                if ($uInfo) {
                    $data['uid'] = $uInfo['did'];
                } else {
                    $data['uid'] = 0;
                }
            }
        }
        if ($model) {
            $useInfo = $model;
        } else {
            //根据控制器获取模块
            $map['dckc'] = request()->controller();
            $map['dcka'] = 'index';
            $useInfo = Db::name('menu')->where($map)->value('dname');
        }
        $data['module'] = $useInfo;
        $data['action'] = $action;
        $data['content'] = $text;
        $data['create_time1'] = time();
        Db::name('record')->insert($data);
    }
}

//CURL
if (!function_exists('curlRequest')) {
    function curlRequest($url, $data)
    {
        $ch = curl_init();
        $res = curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = json_decode(curl_exec($ch), true);
        curl_close($ch);
        return $result;
    }
}

//翻译接口
if (!function_exists('TransQuery')) {
    // 百度翻译开放平台 http://api.fanyi.baidu.com/api/trans/product/apidoc
    function TransQuery($queryData, $lang)
    {
        $api_key = 'rsg3m_zW_lO48hTnm2ZL';
        $baiduTransApi = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
        $data = array(
            'q' => $queryData,
            'appid' => '20190912000333880',
            'salt' => rand(10000, 99999),
            'from' => 'auto',
            'to' => $lang,
        );
        $data['sign'] = md5($data['appid'] . $queryData . $data['salt'] . $api_key);
        $returnData = curlRequest($baiduTransApi, $data);
        return json_encode($returnData);
    }
}


// 编辑排序
if (!function_exists('changeDrank')) {
    function changeDrank($num, $table, $drank, $olddrank = 0, $where = '1=1')
    {
        $endNumber = 99;
        if ($num == 100) $endNumber = 1000000;
        if (!$olddrank) {
            $drankSql = 'drank between ' . $drank . ' and ' . $endNumber;
        } else {
            if ($drank > $olddrank) $drankSql = 'drank between ' . $drank . ' and ' . $endNumber;
            if ($drank < $olddrank) $drankSql = 'drank between ' . $drank . ' and ' . ($olddrank - 1);
        }
        $res = Db::name($table)->where($where)->where($drankSql)->select();
        if (!empty($res)) {
            foreach ($res as $k => $v) {
                $ress = Db::name($table)->where('id', $v['id'])->update(['drank' => ($v['drank'] + $num)]);
            }
            return $ress;
        } else {
            return 1;
        }
    }
}

//编辑数据
if (!function_exists('getinfo')) {
    function getinfo($did, $db_name, $field = '*')
    {
        $res = Db::name($db_name)->where('id', $did)->field($field)->find();
        return $res;
    }
}
//获取的是单条数据的信息
if (!function_exists('getlanginfo')) {
    function getlanginfo($db_name, $where)
    {
        if ($where) {
            $info = Db::name($db_name)->where($where)->find();//编辑的数据
            $mkey = $info['mkey'];
        }
        $langname = Db::name('multi_lang')->where(['mkey' => $mkey])->select();//获取多语言的数据
        foreach ($langname as $langnamekey => $langnameval) {
            $info['lang_' . $langnameval['lang']] = $langnameval['content'];
        }
        return $info;
    }
}

//获取对应的语言的内容
if (!function_exists('getlangname')) {
    function getlangname($dbname, $where, $lang)
    {
        $where['lang'] = $lang;
        //获取一种
        $data = Db::name($dbname)->where($where)->select();
        $resdata = implode('/', array_column($data, 'content'));
        return str_replace("/", " / ", $resdata);
    }
}
//获取对应表的所有语言
function getlangres($dbname, $lang, $field = null, $where = array())
{
    $join = [
        ['multi_lang b', 'a.mkey = b.mkey', 'LEFT'],
    ];
    $where['b.lang'] = $lang;
    if (!$field) {
        $field = 'a.*,b.content';
    }
    $data = Db::name($dbname)->field($field)->alias('a')->where($where)->join($join)->select();
    return $data;
}

//获取的语言表的数据
function getlangnames()
{
    $langname = getables('language', ['status' => 1], 'id,name,code');
    //通过name去获取多语言
    foreach ($langname as $langkey => $langval) {
        $mkey = Db::name('dict')->field('abbreviation')->where('content', $langval['name'])->find();
        $langname[$langkey]['name'] = $mkey ? lang($mkey['abbreviation']) : $langval['name'];
    }
    return $langname;
}

//获取对应数据库的语言的名称
if (!function_exists('getmultidata')) {
    function getmultidata($table, $join, $where, $pagelimit = null, $order = 'create_at desc')
    {
        if ($pagelimit) {
            $data = Db::name($table)->alias('a')->join($join)->field('b.*,a.content')->where($where)->limit($pagelimit['start'], $pagelimit['limit'])->order($order)->select();
        } else {
            $data = Db::name($table)->alias('a')->join($join)->field('b.*,a.content')->where($where)->order($order)->select();
        }
        $count = Db::name($table)->alias('a')->join($join)->where($where)->count();
        return array('count' => $count, 'data' => $data);
    }
}

if (!function_exists('getables')) {
    function getables($tab, $where = [], $field = '*', $sortid = '')
    {
        $tabInfo = Db::name($tab)->field($field)->where($where)->order($sortid)->select();
        return $tabInfo;
    }
}
//不能为空
if (!function_exists('notEmpty')) {
    function notEmpty($array)
    {
        foreach ($array as $key => $value) {
            if (isset($_POST['data'])) {
                if (!$_POST['data'][$key]) {
                    $ret['status'] = 2;
                    $ret['msg'] = $value . lang("can't_be_empty") . '!!!';
                    return $ret;
                }
            } else {
                if (!$_POST[$key]) {
                    $ret['status'] = 2;
                    $ret['msg'] = $value . lang("can't_be_empty") . '!!!';
                    return $ret;
                }
            }
        }
        $ret['status'] = 1;
        return $ret;
    }
}

// 获取当前语言
if (!function_exists('is_lang')) {
    function is_lang($lang_type = '')
    {
        if ($lang_type) {
            $admin_id = session('userid');
            if ($admin_id) {
                $language_id = Db::name('language')->where('code', $lang_type)->value('id');
                //改变用户的语言
                Db::name('admin')->where('id', $admin_id)->update(['language_id' => $language_id]);
            }
            cookie('think_var', $lang_type);
        }
        return cookie('think_var');
    }
}

if (!function_exists('getLangData')) {
    function getLangData($langText, $abbreviation, $lang_type)
    {
        switch ($lang_type) {
            case 'zh':
                $data['lang_en'] = $langText . '_en';
                $data['lang_pt'] = $langText . '_pt';
                break;

            case 'en':
                $data['lang_zh'] = $langText . '_zh';
                $data['lang_pt'] = $langText . '_pt';
                break;

            case 'pt':
                $data['lang_zh'] = $langText . '_zh';
                $data['lang_en'] = $langText . '_en';
                break;
        }
        $data['abbreviation'] = $abbreviation;
        return $data;
    }
}
// 判断是否已经存在
if (!function_exists('isIsset')) {
    function isIsset($table, $swhereKey, $whereValue, $where = '1=1')
    {
        $res = Db::name($table)->where($swhereKey, $whereValue)->where($where)->find();
        if ($res) {
            return $res;
        } else {
            return false;
        }
    }
}

if (!function_exists('getTimeDates')) {
    function getTimeDates($time, $lang, $onlyYmd = false)
    {
        if ($onlyYmd) {
            switch ($lang) {
                case 'zh':
                    return date('Y-m-d', $time);
                    break;
                default:
                    return date('d-m-Y', $time);
                    break;
            }
        } else {
            switch ($lang) {
                case 'zh':
                    return date('Y-m-d H:i:s', $time);
                    break;
                default:
                    return date('d-m-Y H:i:s', $time);
                    break;
            }
        }
    }

}


if (!function_exists('getTimeDate')) {
    function getTimeDate($time, $format = 0)
    {
        if (!$time) $time = time();
        switch ($format) {
            case 1:
                return date('Y', $time);
                break;
            case 2:
                return date('m', $time);
                break;
            case 3:
                return date('d', $time);
                break;
            case 4:
                return date('H:i:s', $time);
                break;
            case 5:
                return date('H', $time);
                break;
            case 6:
                return date('W', $time);
                break;
            case 7:
                return date('Y-m-d', $time);
                break;
            case 8:
                return date('d-m-Y', $time);
                break;
            case 9:
                return date('d-m-y H:i:s', $time);
                break;
            case 10:
                return date('Y-m', $time);
                break;
            case 11:
                return date('m-Y', $time);
                break;
            case 12:
                return date('y-m-d H:i:s', $time);
                break;
            case 13:
                return date('m-d-Y', $time);
                break;
            case 14:
                return date('y-m', $time);
                break;
            case 15:
                return date('y-m-d', $time);
                break;
            default:
                return date('Y-m-d H:i:s', $time);
                break;
        }
    }
}

//获取下一个月的日期
if (!function_exists('getNextMonthDays')) {
    function getNextMonthDays($date)
    {
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
        return array($firstday, $lastday);
    }
}

if (!function_exists('getLanguage')) {
    function getLanguage($lang = '')
    {
        $res = Db::name('language')->where('status', '1')->select();
        foreach ($res as $k => $v) {
            if ($v['code'] == $lang) {
                unset($res[$k]);
                array_unshift($res, $v);
            }
        }
        return $res;
    }
}

if (!function_exists('getNoticLang')) {
    function getNoticLang($lang)
    {
        return getValue('language', ['code' => $lang], 'name');
    }
}
// group 搜索
if (!function_exists('getGroup')) {
    function getGroup($table, $field, $where, $group)
    {
        $res = Db::name($table)->field($field)->where($where)->group($group)->select();
        return $res;
    }
}

// 联表查询
if (!function_exists('getSearch')) {
    function getSearch($table, $alias, $field, $where = "1=1", $join, $order, $whereOr = [], $group = '', $page = '1,1000000')
    {
        $res = Db::name($table)
            ->alias($alias)
            ->join($join)
            ->field($field)
            ->where($where)
            ->whereOr($whereOr)
            ->order($order)
            ->group($group)
            ->page($page)
            // ->fetchSql()
            ->select();
        return $res;
    }
}

// 按多语言类型获取页面文本语言格式
if (!function_exists('getViewMultiLanguage')) {
    function getViewMultiLanguage($switch, $lang = 'zh')
    {
        switch ($switch) {
            case '1':
                $res = 'recovery';    // 正常
                break;
            case '2':
                $res = 'delete';    // 软删除
                break;
            case '3':
                $res = 'hide';      // 隐藏
                break;
            case '4':
                $res = 'off_the_shelf';  // 下架
                break;
            case '5':
                $res = 'clear';  // 清除
                break;
            default:
                $res = $switch;
                break;
        }
        return $res;
    }
}

// 获取单个字段值
if (!function_exists('getValue')) {
    function getValue($table, $where, $value)
    {
        $result = Db::name($table)->where($where)->value($value);
        $result = $result == null ? '' : $result;
        return $result;
    }
}

// 新增数据
if (!function_exists('insertData')) {
    function insertData($table, $insertData)
    {
        $res = Db::name($table)->insertGetId($insertData);
        return $res;
    }
}

// 修改数据
if (!function_exists('updateData')) {
    function updateData($table, $where, $updateData)
    {
        $res = Db::name($table)->where($where)->update($updateData);
        return $res;
    }
}

// 删除数据
if (!function_exists('deleteData')) {
    function deleteData($table, $where, $idArray = array())
    {
        if (empty($idArray)) {
            $res = Db::name($table)->where($where)->delete();
            return $res;
        } else {
            Db::startTrans();
            try {
                foreach ($idArray as $k => $v) {
                    $res = Db::name($table)->where('id', $v)->delete();
                }
                if ($res >= 0) {
                    Db::commit();
                    return array('code' => 2000, 'msg' => lang($table . '__operational_success'));
                } else {
                    return array('code' => 500, 'msg' => lang($table . '__operational_fail'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                return array('code' => 500, 'msg' => $e);
            }
        }
    }
}

// 是否有数据
if (!function_exists('hasData')) {
    function hasData($table, $where)
    {
        $res = Db::name($table)->where($where)->count();
        return $res;
    }
}

// 获取数据
if (!function_exists('getDatas')) {
    function getDatas($table, $field, $where = '1=1', $order = 'id desc', $page = '1,1000000')
    {
        $res = Db::name($table)->field($field)->where($where)->order($order)->page($page)->select();
        return $res;
    }
}


// 获取多语言数据
if (!function_exists('getMultiLangName')) {
    function getMultiLangName($table, $field, $where, $order, $lang = '')
    {
        $resData = getDatas($table, $field, $where, $order);
        if (count($resData) > 1) {
            foreach ($resData as $k => $v) {
                if ($table == 'prochar') {
                    $where1['mkey'] = $v['ctn_note'];
                } else {
                    $where1['mkey'] = $v['mkey'];
                }
                $foreachData = getDatas('multi_lang', ['*'], $where1);
                foreach ($foreachData as $k1 => $v1) {
                    $resData[$k]['name_' . $v1['lang']] = $v1['content'];
                }
            }

        } else if (count($resData) == 1) {
            if ($table == 'prochar') {
                $where1['mkey'] = $resData[0]['ctn_note'];
            } else {
                $where1['mkey'] = $resData[0]['mkey'];
            }
            $foreachData = getDatas('multi_lang', ['*'], $where1);
            foreach ($foreachData as $k => $v) {
                $resData[0]['name_' . $v['lang']] = $v['content'];
            }
        }
        return $resData;
    }
}

if (!function_exists('getTreeParent')) {
    function getTreeParent($table, $field, $where, $data = array())
    {
        $resData = getMultiLangName($table, $field, $where, 'id asc')[0];
        if ($resData['pid'] > 0) {
            $res = getTreeParent($table, $field, ['id' => $resData['pid']], $data);
            array_push($data, $res[0]);
        }
        array_push($data, $resData);
        return $data;
    }
}

if (!function_exists('noticeText')) {
    function noticeText($array, $Wherearray, $noticeString = '不能为空', $type = 'empty')
    {
        foreach ($Wherearray as $k => $v) {
            if ($type == 'empty') {
                if (!$array[$k]) return array('status' => 2, 'msg' => $v . $noticeString);
            } else {
                if (!isset($array[$k])) return array('status' => 2, 'msg' => $v);
            }
        }
    }
}

if (!function_exists('getChildID')) {
    // 获取当前类行下 所以能用的子级
    function getChildID($table, $field, $where, $pid = 0, $data = [])
    {
        $_data = Db::name($table)
            ->field($field)
            ->where($where)
            ->where('pid', $pid)
            // ->fetchSql()
            ->select();
        // return $_data;
        if (!empty($_data)) {
            // array_push($data,$_data);
            foreach ($_data as $k => $v) {
                array_push($data, $v);
                $res = getChildID($table, $field, $where, $v['id'], $data);
                // array_push($data,$res);
            }
        }
        return $data;
    }
}
//获取的是这个数据的上级数据
if (!function_exists('getpostion')) {
    function getpostion($dbname, $id)
    {
        //初始化ID数组
        $array[] = $id;
        do {
            $ids = '';
            $where['id'] = array('in', $id);
            $dbselect = Db::name($dbname)->where($where)->select();
            foreach ($dbselect as $v) {
                $array[] = $v['pid'];
                $ids .= ',' . $v['pid'];
            }
            $ids = substr($ids, 1, strlen($ids));
            $id = $ids;
        } while (!empty($dbselect));
        foreach ($array as $arraykey => $arrayval) {
            if ($arrayval == 0) {
                unset($array[$arraykey]);
            }
        }
        return $array;
    }
}

//国家的显示
if (!function_exists('getcountry')) {
    function getcountry($country_id)
    {
        if ($country_id == 0) {
            $status = lang("universal");
        } elseif ($country_id == 1) {
            $status = lang("BRAZIL");
        } elseif ($country_id == 2) {
            $status = lang("CHINA");
        }
        return $status;
    }
}

if (!function_exists('getImgUrl')) {
    function getImgUrl($pro_id, $size, $type = 'pro', $prochar_id = 0)
    {
        $img = getDatas('pro_img', ['img_url,img_format'], ['pro_id' => $pro_id, 'is_icon' => 1]);
        if (!empty($img)) {
            if ($img[0]['img_format'] && $img[0]['img_url'] != '/icon/0000/0000.jpg') {
                if ($type == 'prochar') $img_url = '/icon/' . $pro_id . '/' . $prochar_id . '_' . $size . '.' . $img[0]['img_format'];
                if ($type == 'pro' || !file_exists(ltrim($img_url, '/')) || $img_url == '/icon/0000/0000_' . $size . '.jpg') $img_url = '/icon/' . $pro_id . '/0_' . $size . '.' . $img[0]['img_format'];
            } else {
                $img_url = '/icon/0000/0000_' . $size . '.jpg';
            }
        } else {
            $img_url = '/icon/0000/0000_' . $size . '.jpg';
        }
        return $img_url;
    }
}


function insertMuitl($mkey, $content)
{
    $langData = getLanguage();
    foreach ($langData as $k => $v) {
        $insertData['mkey'] = $mkey;
        $insertData['content'] = $content;
        $insertData['lang'] = $v['code'];
        $res = insertData('multi_lang', $insertData);
    }
    return $res;
}

// 去除字符串特殊符号
function strFilter($str)
{
    $str = str_replace('`', '', $str);
    $str = str_replace('·', '', $str);
    $str = str_replace('~', '', $str);
    $str = str_replace('!', '', $str);
    $str = str_replace('！', '', $str);
    $str = str_replace('@', '', $str);
    $str = str_replace('#', '', $str);
    $str = str_replace('$', '', $str);
    $str = str_replace('￥', '', $str);
    $str = str_replace('%', '', $str);
    $str = str_replace('^', '', $str);
    $str = str_replace('……', '', $str);
    $str = str_replace('&', '', $str);
    $str = str_replace('*', '', $str);
    $str = str_replace('(', '', $str);
    $str = str_replace(')', '', $str);
    $str = str_replace('（', '', $str);
    $str = str_replace('）', '', $str);
    $str = str_replace('-', '', $str);
    $str = str_replace('_', '', $str);
    $str = str_replace('——', '', $str);
    $str = str_replace('+', '', $str);
    $str = str_replace('=', '', $str);
    $str = str_replace('|', '', $str);
    $str = str_replace('\\', '', $str);
    $str = str_replace('[', '', $str);
    $str = str_replace(']', '', $str);
    $str = str_replace('【', '', $str);
    $str = str_replace('】', '', $str);
    $str = str_replace('{', '', $str);
    $str = str_replace('}', '', $str);
    $str = str_replace(';', '', $str);
    $str = str_replace('；', '', $str);
    $str = str_replace(':', '', $str);
    $str = str_replace('：', '', $str);
    $str = str_replace('\'', '', $str);
    $str = str_replace('"', '', $str);
    $str = str_replace('“', '', $str);
    $str = str_replace('”', '', $str);
    $str = str_replace(',', '', $str);
    $str = str_replace('，', '', $str);
    $str = str_replace('<', '', $str);
    $str = str_replace('>', '', $str);
    $str = str_replace('《', '', $str);
    $str = str_replace('》', '', $str);
    $str = str_replace('.', '', $str);
    $str = str_replace('。', '', $str);
    $str = str_replace('/', '', $str);
    $str = str_replace('、', '', $str);
    $str = str_replace('?', '', $str);
    $str = str_replace('？', '', $str);
    return trim($str);
}

//处理id补0的效果
function numzero($code)
{
    $strlen = strlen($code);
    if ($code) {
        if ($strlen == 1) {
            $code = '000' . $code;
        }
        if ($strlen == 2) {
            $code = '00' . $code;
        }
        if ($strlen == 3) {
            $code = '0' . $code;
        }
        if ($strlen >= 4) {
            $code = $code;
        }
    } else {
        $code = '';
    }
    return $code;
}

// 根据产品/产品角色获取信息
function getProAndProchar($data, $lang, $imgSize = 48)
{
    if (isset($data['pro_id']) && $data['pro_id']) $where['zu.id'] = $data['pro_id'];
    if (isset($data['prochar_id']) && $data['prochar_id']) $where['pc.id'] = $data['prochar_id'];
    $where['mu.lang'] = $lang;
    $join = [
        ['multi_lang mu', 'zu.mkey = mu.mkey', 'LEFT'],
        ['pro_brand b', 'zu.brand_id = b.id', 'LEFT', 'LEFT'],
        ['prochar pc', 'zu.id = pc.pro_id', 'LEFT']
    ];
    $list = getSearch('pro', 'zu', ['zu.id pro_id,zu.brand_id,mu.content pro_name,b.name brand_name,pc.id prochar_id,pc.model,pc.package_qty,pc.ctn_size,pc.ctn_kgs,pc.ctn_m3,pc.qty prochar_qty'], $where, $join, 'zu.id desc');
    foreach ($list as $k => $v) {
        $list[$k]['img_url'] = $v['prochar_id'] ? getImgUrl($v['pro_id'], $imgSize, 'prochar', $v['prochar_id']) : getImgUrl($v['pro_id'], $imgSize, 'pro', $v['prochar_id']);
    }
    if ((isset($data['pro_id']) && $data['pro_id']) || (isset($data['prochar_id']) && $data['prochar_id'])) {
        if (!empty($list)) $list = $list[0];
    }
    return $list;
}

// 根据产品分类和关键字获取产品
function getProList($data, $lang)
{
    $where['mp.lang'] = $lang;
    if (isset($data['procat_id']) && $data['procat_id']) $where['c.procat_id'] = $data['procat_id'];
    if (isset($data['searchText']) && $data['searchText']) $where['zu.id|mp.content|ph.model|ph.id'] = ['like', "%" . $data['searchText'] . "%"];
    $join = [
        ['multi_lang mp', 'zu.mkey = mp.mkey', 'LEFT'],
        ['prochar ph', 'zu.id = ph.pro_id'],
        ['pro2cate c', 'zu.id = c.pro_id', 'LEFT']
    ];
    $proList = getSearch('pro', 'zu', ['zu.id pro_id,zu.mkey pro_mkey,zu.brand brand_name,ph.*,mp.content pro_name'], $where, $join, 'zu.id desc', '', '', '1,10');
    if (!empty($proList)) {
        $proList = array_unique_fb($proList);
        foreach ($proList as $k => $v) {
            $v['model'] = $v['model'] ? $v['model'] . '/' : '';
            $v['brand_name'] = $v['brand_name'] ? $v['brand_name'] . '/' : '';
            // $proList[$k]['feature'] = $v['id']. '/'.$v['brand_name'].$v['model'].$v['content'];
        }
    }
    // dump($proList);die;
    return $proList;
}

// 去重
function array_unique_fb($array2D)
{

    foreach ($array2D as $k => $v) {
        $vv = '';
        foreach ($v as $k1 => $v1) {
            $vv .= $k1 . '--' . $v1 . ',';
        }
        $temp[] = rtrim($vv, ',');
    }
    $temp = array_unique($temp);//去掉重复的字符串,也就是重复的一维数组
    foreach ($temp as $k2 => $v2) {
        $res = explode(",", $v2);//再将拆开的数组重新组装
        foreach ($res as $k3 => $v3) {
            $res1 = explode("--", $v3);
            $returnData[$k2][$res1[0]] = $res1[1];
        }
    }
    return $returnData;
}

// 获取产品角色特征
function getFeature($pro_id, $lang, $prochar_id = 0)
{
    $where['pro_id'] = $pro_id;
    if ($prochar_id) $where['id'] = $prochar_id;
    $prochar = getDatas('prochar', ['*'], $where);
    // dump($prochar);die;
    if (!empty($prochar)) {
        foreach ($prochar as $k => $v) {

            $prochar2feature = getDatas('profeature2char', ['*'], ['prochar_id' => $v['id']]);
            $getLanguage = getLanguage($lang);
            $returnFeatures['feature'] = '';
            if (!empty($prochar2feature)) {
                foreach ($prochar2feature as $k1 => $v1) {
                    $feature_ = getMultiLangName('proattr_value', ['*'], ['id' => $v1['profeature_value_id']], 'id asc');
                    $feature = $feature_ ? $feature_[0] : [];
                    if (isset($feature['name_' . $lang])) $returnFeatures['feature'] .= $feature['name_' . $lang] ? $feature['name_' . $lang] . ' / ' : '';
                }
                foreach ($returnFeatures as $krtrim => $vrtrim) {
                    $returnFeatures[$krtrim] = rtrim($returnFeatures[$krtrim], ' / ');
                }
            }

            $returnFeatures['id'] = $v['id'];
            $returnFeature = $returnFeatures;
            $returnFeature['pro_name'] = getValue('multi_lang', ['mkey' => 'pro_' . $v['pro_id'], 'lang' => $lang], 'content');
            $returnFeature['model'] = $v['model'];
            $returnFeature['prochar_id'] = $v['id'];
            $returnFeature['pro_id'] = $pro_id;
            $brand_name = getSearch('pro', 'zu', ['b.name'], ['zu.id' => $v['pro_id']], [['pro_brand b', 'zu.brand_id = b.id']], 'zu.id desc');
            if (!empty($brand_name)) $returnFeature['brand_name'] = $brand_name['0']['name'];

            $returnFeature['isCheck'] = false;
            if ($prochar_id == $v['id']) $returnFeature['isCheck'] = true;
        }
    } else {
        $returnFeature = [];
    }
    return $returnFeature;
}

//获取配置表的数据
function getconfig()
{
    $rs = Db::name('sys_variable')->field('id,name')->select();
    //通过变量id去获取对应的值
    foreach ($rs as $rskey => $rsval) {
        $rs[$rskey]['value'] = implode(',', array_column(Db::name('sys_variable_value')->where('variable_id', $rsval['id'])->select(), 'value'));
    }
    foreach ($rs as $value) {
        $array[$value['name']] = $value['value'];
    }
    return $array;
}

// 计算产品角色体积，尺寸单位是cm，因此计算体积立方的时候 要除 1000000
function ctnM3($ctnSize)
{
    $ctnSize = str_replace('*', 'x', $ctnSize);
    $ctnSize = str_replace('X', 'x', $ctnSize);
    $ctnSize = str_replace('+', 'x', $ctnSize);
    $ctnSize = explode('x', $ctnSize);
    $ctn_m3 = 1;
    foreach ($ctnSize as $k => $v) {
        $ctn_m3 *= ($v ? $v : 0);
    }
    $ctn_m3 = round($ctn_m3 / 1000000, 3);;
    return $ctn_m3;
}

//获取业务员的名称
function getsalername()
{
    $admin = session('admin');
    //业务员的id和名称
    //管理员 总经理 巴西总经理 市场总监 客户经理 销售主管 业务组长 高级业务员 业务员 实习业务员
    //销售代表
    if ($admin['position_id'] == 1) {
        $poid = ['1', '2', '3', '5', '10', '11', '13', '14', '15', '16', '12'];
    } elseif ($admin['position_id'] == 2) {
        $poid = ['2', '3', '5', '10', '11', '13', '14', '15', '16', '12'];
    } elseif ($admin['position_id'] == 3) {
        $poid = ['3', '5', '10', '11', '13', '14', '15', '16', '12'];
    } elseif ($admin['position_id'] == 5) {
        $poid = ['5', '10', '11', '13', '14', '15', '16', '12'];
    } elseif ($admin['position_id'] == 10) {
        $poid = ['10', '11', '13', '14', '15', '16', '12'];
    } elseif ($admin['position_id'] == 11) {
        $poid = ['11', '13', '14', '15', '16'];
    } elseif ($admin['position_id'] == 13) {
        $poid = ['13', '14', '15', '16'];
    } else {
        $poid = $admin['position_id'];
    }
    $mapmanage['position_id'] = ['in', $poid];
    $managename = getables('admin', $mapmanage, 'id,nickname');
    return $managename;
}

// 获取当月第一天和最后一天时间
function getthemonth($date = '', $type = false)
{
    if (!$date) $date = date("Y-m-d", time());
    $firstday = date("Y-m-01", strtotime($date));
    $lastday = date("Y-m-d", strtotime("$firstday +1 month -1 day"));
    if ($type) {
        $firstday = strtotime($firstday);
        $lastday = strtotime($lastday);
    }
    return array($firstday, $lastday);
}

//处理两个时间之前的间隔
function gettime($begin_time, $end_time)
{
    if ($end_time <= $begin_time) {
        return ['hour' => 0, 'min' => 0, 'sec' => 0];
    }
    $timediff = $end_time - $begin_time;
    // 时
    $hours = intval($timediff / 3600);

    $remain = $timediff % 3600;
    //分
    $mins = intval($remain / 60);
    //秒
    $secs = $remain % 60;

    if (strlen($hours) == 1) {
        $hours = '0' . $hours;
    }
    if (strlen($mins) == 1) {
        $mins = '0' . $mins;
    }
    if (strlen($secs) == 1) {
        $secs = '0' . $secs;
    }
    $time = ['hour' => $hours, 'min' => $mins, 'sec' => $secs];
    return $time;
}

/**
 * 二维数组根据某个字段排序
 * @param array $array 要排序的数组
 * @param string $keys 要排序的键字段
 * @param string $sort 排序类型  SORT_ASC     SORT_DESC
 * @return array 排序后的数组
 */
function arraySort($array, $keys, $sort = SORT_DESC)
{
    $keysValue = [];
    foreach ($array as $k => $v) {
        $keysValue[$k] = $v[$keys];
    }
    array_multisort($keysValue, $sort, $array);
    return $array;
}

/*
 * $data 入库信息
 * $po_ids 入库合同ids
 * $container_id 货柜id
 * $BRL2CNY汇率，$cost 系统变量（货柜费用）
 */
function cifpro($valdata, $po_ids, $container_id, $BRL2CNY, $cost)
{
    //如果提交的产品含有配件，先更新配件的cif
    $res = gexinprosale($valdata, $BRL2CNY, $cost, $po_ids, $container_id);
    //表示已经更新了配件的cif
    if ($res == 1) {
        $cif = 0;
        //产品
        if ($valdata['is_item'] == 0) {
            //采购价格/汇率
            $cghls = $valdata['price'] / $BRL2CNY;
            // 每立方费用
            if ($valdata['cost'] != 0) {
                $cbm_value = $valdata['cost'] / $valdata['sum_cbm'];
            } else {
                $cbm_value = $cost / $valdata['sum_cbm'];
            }
            //运费 （po_pack.ctn_m3/po_pack.ctn_qty）* (container.cost/container.sum_cbm)  产品体积*每立方费用
            $yffys = ($valdata['ctn_m3'] / $valdata['ctn_qty']) * $cbm_value;
            //获取这个产品下的配件产品id和配件产品的角色id
            $mapstore['pro_id'] = $mappro_item['pro_id'] = $valdata['pro_id'];
            $mapstore['prochar_id'] = $mappro_item['prochar_id'] = $valdata['prochar_id'];

            //该产品的配件产品id和配件角色id
            $pro_idsprochids = Db::name('pro_item')->field('pro_id2item,prochar_id2item')->where($mappro_item)->select();

            $itemprocif = 0;//配件产品的cif合计
            if ($pro_idsprochids) {
                //存在配件
                foreach ($pro_idsprochids as $pro_idskey => $pro_idsval) {
                    $mapitems['pro_id'] = $pro_idsval['pro_id2item'];
                    $mapitems['prochar_id'] = $pro_idsval['prochar_id2item'];
                    //获取到配件产品id角色id 去获取该配件cif
                    $vals = getValue('pro_sale', $mapitems, 'cif');
                    if ($vals) {
                        $itemprocif += $vals;
                    }
                }

            }
            //其他费用
            $qtfys = getValue('pro_sale', ['pro_id' => $valdata['pro_id'], 'prochar_id' => $valdata['prochar_id']], 'add_value');
            if (!$qtfys) {
                $qtfys = 0;
            }
            //分摊费用
            $ftfys = getproft($po_ids, $valdata['pro_id'], $valdata['prochar_id']);

            //入库总价 =货柜产品数量 *（采购价格/汇率+运费+配件成本+分摊费用+其他费用）
            $ruprice = $valdata['qty'] * ($cghls + $yffys + $itemprocif + $ftfys + $qtfys);

            //获取这个产品的库存数量
            $mapstore['warehouse_id'] = 0;
            $mapstore['place_id'] = 0;
            $qtystore = getValue('store', $mapstore, 'qty');//产品库存
            if (!$qtystore) {
                $qtystore = 0;
            }
            //（通过产品id，产品角色id，获取当前的cif）
            $cifproinfo = Db::name('pro_sale')->where($mappro_item)->find();
            if ($cifproinfo) {
                $cif = $cifproinfo['cif'];
            }

            //库存总价 当前的CIF*库存数量
            $storeprice = $cif * $qtystore;

            //新成本的cif  （入库总价+库存总价）/（入库数量+库存数量）
            $newcif = ($ruprice + $storeprice) / ($valdata['qty'] + $qtystore);

            //更新成本价格
            $update['cif'] = $newcif;// 最新的cif
            $update['item_value'] = $itemprocif;//成本合计(也就是配件成本cif合计)
            $update['tran_fee'] = $yffys;//运费
            $update['cbm_value'] = $cbm_value;//每立方价格
            $update['price'] = $valdata['price'];//采购价格
            if ($cifproinfo) {
                //更新
                Db::name('pro_sale')->where($mappro_item)->update($update);
            } else {
                $update['pro_id'] = $valdata['pro_id'];//产品id
                $update['prochar_id'] = $valdata['prochar_id'];//产品角色id
                //添加
                Db::name('pro_sale')->insert($update);
            }
        }
    }
}

/*
 * 入库总价=货柜产品数量*（采购价格/汇率+分摊费用+配件成本+运费+其他费用）
 * 库存总价=当前的cif*库存数量
 */
function gexinprosale($prolist, $BRL2CNY, $cost, $po_ids, $container_id)
{
    $cif = 0; //配件陈本
    //配件
    if ($prolist['is_item'] == 1) {
        //采购价格/汇率
        $cghl = $prolist['price'] / $BRL2CNY;
        //每立方的费用
        if ($prolist['cost'] != 0) {
            $cbm_value = $prolist['cost'] / $prolist['sum_cbm'];
        } else {
            $cbm_value = $cost / $prolist['sum_cbm'];;
        }
        //运费 （po_pack.ctn_m3/po_pack.ctn_qty）* (container.cost/container.sum_cbm)  产品体积*每立方费用
        $yunfei = ($prolist['ctn_m3'] / $prolist['ctn_qty']) * $cbm_value;
        //其他费用
        $qtfy = getValue('pro_sale', ['pro_id' => $prolist['pro_id'], 'prochar_id' => $prolist['prochar_id']], 'add_value');
        if (!$qtfy) {
            $qtfy = 0;
        }
        //分摊费用
        $ftfy = getproft($po_ids, $prolist['pro_id'], $prolist['prochar_id']);
        //入库总价= 货柜产品数量 *（采购价格/汇率+运费+分摊费用+其他费用+配件成本）（配件没有配件成本）
        $ruprice = $prolist['qty'] * ($cghl + $yunfei + $qtfy + $ftfy);

        $mapstore['warehouse_id'] = 0;
        $mapstore['place_id'] = 0;
        $mapitemo['pro_id'] = $mapstore['pro_id'] = $prolist['pro_id'];
        $mapitemo['prochar_id'] = $mapstore['prochar_id'] = $prolist['prochar_id'];
        $qtystore = getValue('store', $mapstore, 'qty');//产品库存
        //查找不到，总库存就是0
        if (!$qtystore) {
            $qtystore = 0;
        }
        //当前的CIF
        $cifinfo = Db::name('pro_sale')->where($mapitemo)->find();
        if ($cifinfo) {
            $cif = $cifinfo['cif'];
        }
        //库存总价 当前的CIF*库存数量
        $storeprice = $cif * $qtystore;

        //新成本的cif  （入库总价+库存总价）/（入库数量+库存数量）
        $newcif = ($ruprice + $storeprice) / ($prolist['qty'] + $qtystore);

        //更新成本价格
        $update['cif'] = $newcif;//成本合计 最新的cif（也就是这个配件的cif）
        $update['tran_fee'] = $yunfei;//运费
        $update['cbm_value'] = $cbm_value;//每立方价格
        $update['price'] = $prolist['price'];//采购价格
        $update['update_at'] = time();//时间
        if ($cifinfo) {
            //更新
            Db::name('pro_sale')->where($mapitemo)->update($update);
        } else {
            $update['pro_id'] = $prolist['pro_id'];
            $update['prochar_id'] = $prolist['prochar_id'];
            //添加
            Db::name('pro_sale')->insert($update);
        }
    }
    return 1;
}

/*
 * 入库含有的合同$po_ids
 * 入库产品$pro_id
 * 入库产品角色$prochar_id
 * 获取这个合同有这个产品的合同id
 */
function getproft($po_ids, $pro_id, $prochar_id)
{
    $map['po_id'] = array('in', $po_ids);
    $map['pro_id'] = $pro_id;
    $map['prochar_id'] = $prochar_id;
    $proid = implode(',', array_column(Db::name('buy_po_pack')->where($map)->select(), 'po_id'));//入库含有该产品的合同
    //该产品是否是有分摊
    $mapcost['po_id'] = array('in', $proid);
    $mapcost['apportion'] = 1;
    $po_idarray = Db::name('buy_po_cost')->field('po_id,sum(amount) as sumamount')->where($mapcost)->group('po_id')->select();//入库需要分摊的合同以及该合同需要分摊费用合计
    if ($po_idarray) {
        foreach ($po_idarray as $po_idarraykey => $po_idarrayval) {
            //该合同产品的数量
            $sumqty = array_sum(array_column(Db::name('buy_po_pack')->field('(qty*ctn_qty) as sumqty')->where(['po_id' => $po_idarrayval['po_id']])->select(), 'sumqty'));
            //分摊费用合计/合同产品数量
            $po_idarray[$po_idarraykey]['pjfyval'] = $po_idarrayval['sumamount'] / $sumqty;
        }
        $sumpjfyval = array_sum(array_column($po_idarray, 'pjfyval'));//合计分摊费用
        $countnum = count($po_idarray);//个数
        $ftfynum = $sumpjfyval / $countnum;
    } else {
        $ftfynum = 0;
    }
    //该产品的分摊费用
    return $ftfynum;
}

/*
 * 取消入仓时，更新产品的cif
 * a = 当前库存数量 * 当前CIF
 * b = 货柜的数量(被取消的产品数量) * 货柜的CIF（采购价格/汇率+分摊费用+配件成本+运费+其他费用）
 * c = 当前库存数量 - 货柜的数量(被取消的产品数量)
 * 更新后的CIF = (a-b)/c
 */
function quxiaocifpro($data)
{
    $itemprocif = 0;//配件产品的cif合计
    //取消的这个产品在这个货柜存在的合同
    $mapcontain['container_id'] = $data['container_id'];
    $mapcontain['pro_id'] = $data['pro_id'];
    $mapcontain['prochar_id'] = $data['prochar_id'];
    $pro_ids = getables('buy_po_pack', $mapcontain, 'po_id');
    $po_ids = implode(',', array_unique(array_column($pro_ids, 'po_id')));
    $BRL2CNY = getconfig()['BRL2CNY'];
    $cost = getconfig()['COST_CBM'];
    $map['warehouse_id'] = $map['place_id'] = 0;
    $map['pro_id'] = $data['pro_id'];
    $map['prochar_id'] = $data['prochar_id'];
    $proqty = getValue('store', $map, 'qty');//当前库存
    $cif = getValue('pro_sale', ['pro_id' => $data['pro_id'], 'prochar_id' => $data['prochar_id']], 'cif');//当前cif

    //采购价格/汇率
    $cghl = $data['price'] / $BRL2CNY;
    //分摊费用
    $ftfy = getproft($po_ids, $data['pro_id'], $data['prochar_id']);
    //配件成本
    if ($data['is_item'] == 0) {
        //该产品的配件产品id和配件角色id
        $pro_idsprochids = Db::name('pro_item')->field('pro_id2item,prochar_id2item')->where(['pro_id' => $data['pro_id'], 'prochar_id' => $data['prochar_id']])->select();
        if ($pro_idsprochids) {
            //存在配件
            foreach ($pro_idsprochids as $pro_idskey => $pro_idsval) {
                $mapitems['pro_id'] = $pro_idsval['pro_id2item'];
                $mapitems['prochar_id'] = $pro_idsval['prochar_id2item'];
                //获取到配件产品id角色id 去获取该配件cif
                $vals = getValue('pro_sale', $mapitems, 'cif');
                if ($vals) {
                    $itemprocif += $vals;
                }
            }

        }
    }
    //运费
    //每立方的费用（货柜费用/货柜体积）
    if ($data['cost'] != 0) {
        $cbm_value = $data['cost'] / $data['sum_cbm'];
    } else {
        $cbm_value = $cost / $data['sum_cbm'];;
    }
    //运费 （po_pack.ctn_m3/po_pack.ctn_qty）* (container.cost/container.sum_cbm)  产品体积*每立方费用
    $yunfei = ($data['ctn_m3'] / $data['ctn_qty']) * $cbm_value;
    //其他费用
    $qtfys = getValue('pro_sale', ['pro_id' => $data['pro_id'], 'prochar_id' => $data['prochar_id']], 'add_value');
    if (!$qtfys) {
        $qtfy = 0;
    }
    $cifone = $proqty * $cif;
    $ciftwo = $data['qty'] * ($cghl + $ftfy + $itemprocif + $yunfei + $qtfys);
    $cifthree = $proqty - $data['qty'];
    $cif = $cifthree == 0 ? 0 : ($cifone - $ciftwo) / $cifthree;//取消后的cif
    $update['cif'] = $cif;
    $update['update_at'] = time();
    Db::name('pro_sale')->where(['pro_id' => $data['pro_id'], 'prochar_id' => $data['prochar_id']])->update($update);
}

/**
 *   判断是否短时间内 重复提交数据
 *   $data:待新增数据
 *   $type:  compare:比较两组数据是否全等，empty:清理session
 **/
function isAdd($admin_id, $type, $data = [])
{
    if ($type == 'compare') {
        if (session('addText_admin_' . $admin_id) && session('addText_admin_' . $admin_id) === serialize($data)) {
            return true;
        } else {
            session('addText_admin_' . $admin_id, serialize($data));
            return false;
        }
    } else if ($type == 'empty') {
        session('addText_admin_' . $admin_id, null);
    }
}


// 获取当前页面的按钮权限
function viewAuth($admin_id = 0)
{
    $admin = $admin_id ? Db::name('admin')->where(['id' => $admin_id])->find() : session('admin');
    $auth_ids = '';

    $where['control'] = $controller = request()->controller();
    $where['option'] = $action = request()->action();
    if ($controller == 'Index' && $action == 'index') return;
    $pid = getValue('menu', $where, 'id');
    // dump($pid);die;
    if ($admin['position_id'] == 1) {
        $auth_idArr = getDatas('menu', ['id'], ['pid' => $pid]);
        $auth_ids = implode(',', array_column($auth_idArr, 'id'));
    } else {
        $auth_ids_ = $admin['auth_ids'];
        if ($auth_ids_) {
            if ($pid) {
                $auth_idArr = getDatas('menu', ['id'], ['pid' => $pid, 'id' => ['in', $auth_ids_]]);
                $auth_ids = implode(',', array_column($auth_idArr, 'id'));
            }
        }
    }
    return $auth_ids;
}


// 获取子级职务人员
function getChildAdmin()
{
    $admin = session('admin');
    $childadmin_ids = '';
    // 网站管理员和CEO统一使用一个代号，前端只用判断一次
    if ($admin['position_id'] == 1 || $admin['position_id'] == 2) {
        $childadmin_ids = '1';
    } else {
        // 获取子职务
        $childposition = getDatas('position', ['id'], ['pid' => $admin['position_id']]);
        $childposition_ids = implode(array_column($childposition, 'id'), ',');
        // 根据职务获取人员
        $childadmin = getDatas('admin', ['id'], ['position_id' => ['in', $childposition_ids]]);
        $childadmin_ids = implode(array_column($childadmin, 'id'), ',');

        $childadmin_ids = $childadmin_ids ? $childadmin_ids . ',' . $admin['id'] : $childadmin_ids;
    }
    return $childadmin_ids;
}

//图片上传
if (!function_exists('uploads')) {
    /*
     * 文件对象
     * 上传路径
     */
    function uploads($file, $movepath)
    {
        //获取上传图片的对象
        if (empty($file)) {
            return array('status' => 0, 'msg' => '上传文件不能为空');
            exit;
        }
        //将文件从临时的目录转到上传的目录(public/uplads)  //限制大小300kb
        $info = $file->validate(['size' => 300 * 1024, 'ext' => 'jpg,png,gif,jpeg'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $movepath);
        if (!$info) {
            //上传错误
            $error = $file->getError();
            return array('status' => 0, 'msg' => $error);
            exit;
        } else {
            //拼接图片的访问路径
            $img = DS . 'uploads' . DS . $movepath . DS . $info->getSaveName();
            $img = str_replace('\\', '/', $img);
            //上传成功
            return array('status' => 1, 'msg' => '上传成功', 'imgurl' => $img);
            exit;
        }
    }
}



